import { Model, Effect, SubscriptionsMapObject } from "dva-core-ts";
import { Reducer } from "redux";

export interface CountState {
  num: number;
}

interface CountModel extends Model {
  namespace: "count";
  state: CountState;
  reducers: {
    setState: Reducer<CountState>;
  };
  effects: {
    asyncAdd: Effect;
  };
  subscriptions: SubscriptionsMapObject;
}

const initialState: CountState = {
  num: 100,
};

const delay = (time: number) => {
  console.log("time", time);
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(666);
    }, time);
  });
};

const countModel: CountModel = {
  namespace: "count",
  state: initialState,
  reducers: {
    setState(state = initialState, { payload }) {
      return {
        ...state,
        num: state.num + payload,
      };
    },
  },
  effects: {
    *asyncAdd({ payload }, { call, put }) {
      const res = yield call(delay, 2000);
      console.log(res);
      yield put({
        type: "setState",
        payload,
      });
    },
  },
  subscriptions: {
    setup({ dispatch }) {
      // console.log("dispatch", dispatch);
      console.log("init");
      // 可以初始化initialState
    },
  },
};

export default countModel;
